<?php

namespace addons\yungift\controller;

use addons\yungift\library\Logic;
use addons\yungift\model\Config;
use addons\yungift\model\UserAuth;
use think\addons\Controller;
use think\Session;

/**
 * 页面
 */
class Web extends Controller
{
    protected $noNeedLogin = ['*'];
    protected $layout = '';

    public function connect()
    {
        $url = $this->request->request('url', $this->request->server('HTTP_REFERER', '/', 'trim'), 'trim');
        if (! $url) {
            $this->error('参数错误');
        }
        Session::set('redirectUrl', $url);

        // 跳转到登录授权页面
        $state = md5(uniqid(rand(), true));
        Session::set('state', $state);
        $params = [
            'appid'         => Config::getGroupAttribute(Config::GROUP_MP, 'app_id'),
            'redirect_uri'  => addon_url('yungift/web/callback', [], false, true),
            'response_type' => 'code',
            'scope'         => 'snsapi_base',
            'state'         => $state,
        ];
        $authUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize';
        $authUrl .= '?' . http_build_query($params) . '#wechat_redirect';
        $this->redirect($authUrl);
    }

    public function callback()
    {
        $code = $this->request->get('code');
        if (! $code) {
            $this->error('code不能为空');
        }
        if (isset($params['state']) && $params['state'] != Session::get('state')) {
            $this->error('state不正确');
        }
        $userInfo = Logic::getMpCodeData($code);

        // 成功后返回之前页面
        $url = Session::has('redirectUrl') ? Session::pull('redirectUrl') : '';
        if (! $url) {
            $this->error('没有跳转地址');
        }
        $authKey = Logic::getUserAuthKey($userInfo['openid'], UserAuth::SOURCE_MP);
        $url .= (strpos($url, '?') !== false ? '&' : '?') . 'auth_key=' . $authKey;
        $this->redirect($url);
    }
}
